<template>
  <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="公告标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入公告标题" />
      </el-form-item>
      <el-form-item label="公告内容" prop="content">
        <el-input
          type="textarea"
          :rows="6"
          v-model="form.content"
          placeholder="请输入公告内容"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio label="0">草稿</el-radio>
          <el-radio label="1">立即发布</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addNotice, updateNotice, getNotice } from '@/api/notice'

export default {
  name: 'NoticeForm',
  data() {
    return {
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      form: {
        id: undefined,
        title: '',
        content: '',
        status: '0'
      },
      rules: {
        title: [
          { required: true, message: '公告标题不能为空', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '公告内容不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 显示对话框
    show(row) {
      this.reset()
      if (row) {
        this.form.id = row.id
        this.title = '修改公告'
        getNotice(row.id).then(response => {
          this.form = response.data
        })
      } else {
        this.title = '新增公告'
      }
      this.open = true
    },
    // 重置表单
    reset() {
      this.form = {
        id: undefined,
        title: '',
        content: '',
        status: '0'
      }
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.id) {
            updateNotice(this.form).then(() => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.$emit('refresh')
            })
          } else {
            addNotice(this.form).then(() => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.$emit('refresh')
            })
          }
        }
      })
    },
    cancel() {
      this.open = false
    }
  }
}
</script>
